<?php

namespace app\common\model;

use think\Model;
use think\Db;

class SystemMsg extends Model
{
    protected $table = 'system_msg';
    protected $pk = 'system_msg_id';

    public static function getSystemMercahnt($pagesize)
    {
        $where['system_msg_type'] = ['in', [2, 3]];
        $where['system_receiver_type'] = ['eq', 2];
        $data = self::alias('a')
            ->field('a.system_msg_id,a.system_msg_create_time,b.system_msg_content,b.system_msg_content_create_time,b.system_msg_title')
            ->join('system_msg_content b', 'a.system_msg_content_id=b.system_msg_content_id', 'left')
            ->where($where)
            ->order('a.system_msg_id', 'desc')
            ->paginate($pagesize);
        foreach ($data as $k => &$v) {
            $v['system_msg_create_time'] = date('Y-m-d H:i:s', $v['system_msg_create_time']);
        }
        return $data;
    }

    public static function GetMSG($pagesize)
    {
        // 获取商家注册时间(只获取商家注册后的系统消息)
        $reg_time = Db('merchant')
            ->where('merchant_id', session('merchant.merchant_id'))
            ->value('merchant_reg_time');

        $data = Db("message")
            ->where('message_push_type', 4)
            ->where('message_is_delete', 0)
            ->where('message_create_time', '>=', intval($reg_time))
            ->order('message_id desc')
            ->paginate($pagesize);
        return $data;
    }

    public static function GetOrderMSG($pagesize)
    {
        $keyword = input('param.keyword');
        return Db('message_order')
                ->where('merchant_id', session('merchant.merchant_id'))
                ->where('type', 1)
                ->whereLike('content', '%'.$keyword.'%')
                ->order('id', 'desc')
                ->paginate($pagesize);
    }

    //发送订单消息给用户
    public static function sendOrderMsg($params) {
        $data = [];
        $aNesFields = ['order_id','merchant_id','user_id','title','content'];
        foreach ($aNesFields as $field) {
            if (isset($params[$field])){
                $data[$field] = $params[$field];
            }
        }
        if (empty($data)) return false;
        $data['type'] = 2;
        $data['is_read'] = 0;
        $data['create_time'] = time();
        return Db('message_order')->insert($data);
    }



}